<?php

namespace McUser\Model;
use Common\Model\CommonModel;

/*
 *  Copyright (c) 2014 The CCP project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a Beijing Speedtong Information Technology Co.,Ltd license
 *  that can be found in the LICENSE file in the root of the web site.
 *
 *   http://www.yuntongxun.com
 *
 *  An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

class McUserModel extends CommonModel {

	protected $tableName = 'users';
	
	/*
	*	生成随机字符串
	*/
	function getRandChar($length){
	   $str = null;
	   // $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
	   $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	   $max = strlen($strPol)-1;

	   for($i=0;$i<$length;$i++){
	    	$str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
	   }

	   return $str;
  	}

	/*
	*	检查手机号是否已经注册 ( 发送验证码是, 会检查手机是否已经注册. )
	*/
	public function check_mobile_registered($mobile){
		$where['mobile']=$mobile;
	     
	    $result = $this -> where($where)->count();
	    if($result){
	        return true;
	    }
	    else{
	    	return false;
	    }
	}

	/*
	*	用户登陆函数	( 暂时 没有 用到这个函数 )
	*/
	public function login($mobile, $pass){

		$filter = array(
			'mobile' => $mobile,
			'user_pass' => $pass
			);

		$rejson = array(
				"retCode" => "1",
				"retMsg" => "Success");

		/* 查找是否有这行记录 */
		$user_info = $this->where($filter)->find();

		/*
		dump($user_info);
		*/

		if($user_info){

			/* 保存此次登陆时间 和 登陆IP */
			$genXin['last_login_ip'] = get_client_ip();
			$genXin['last_login_time'] = date('Y-m-d H:i:s', time());

			$this -> where(array('id' => $user_info['id']))->save($genXin);						
		}
		else{
			/* 手机号码或密码错误. */
			$reJson['retCode'] = "-105";
			$code = C('retJson');
			$rejson['retMsg'] = $code['-105'];
		}

		return $reJson;
	}

	/*
	*	用手机号码登陆
	*/
	public function mobile_login($mobile, $pass){
        
        $userID = $this -> get_userID_by_mobile($mobile);

        return $this -> userID_login($userID, $pass);
    }

    /*
    *	用户ID登录
    */
    public function userID_login($userID, $pass){
        
        $where['id']=$userID;        
        $result = $this -> where($where)->find();
        
        if(!empty($result)){
            if(sp_compare_password($pass, $result['user_pass'])){
                
                // $_SESSION["user"]=$result;

                // 写入此次登录信息                
                $data = array(
                    'last_login_time' => date("Y-m-d H:i:s"),
                    'last_login_ip' => get_client_ip(0,true),
                );
                $this->where(array('id'=>$result["id"]))->save($data);

                $redirect=empty($_SESSION['login_http_referer'])?__ROOT__."/":$_SESSION['login_http_referer'];
                $_SESSION['login_http_referer']="";
        
        		/* 登陆成功 */
        		$result['retCode'] = '1';
            }
            else{
            	/* 手机号码或密码错误. */
                $result['retCode'] = '-105';
            }
        }
        else{
        	/* 手机号码或密码错误. */
            $result['retCode'] = '-105';
        }

        return $result;
    }

    /*
    *	管理员登录
    */
    public function login_admin($userAdmin, $passAdmin){
        
        $where['user_login']=$userAdmin;        
        $result = $this -> where($where)->find();
        
        if(!empty($result)){
        	if( $result['user_type'] != '1' )
        		return false ;

            if(sp_compare_password($passAdmin, $result['user_pass'])){
                
                // $_SESSION["user"]=$result;

                // 写入此次登录信息                
                $data = array(
                    'last_login_time' => date("Y-m-d H:i:s"),
                    'last_login_ip' => get_client_ip(0,true),
                );
                $this->where(array('id'=>$result["id"]))->save($data);

                $redirect=empty($_SESSION['login_http_referer'])?__ROOT__."/":$_SESSION['login_http_referer'];
                $_SESSION['login_http_referer']="";
        
        		/* 登陆成功 */
        		return true;
            }
        }

        return false ;
    }

    /*
    *	根据手机号码, 查出用户ID
    */
    public function get_userID_by_mobile($mobile){
        
        $where['mobile']=$mobile;        
        $userID = $this -> where($where)->getfield('id');
        
        return $userID;
    }

	/*
	*	保存注册信息.
	*/ 
	public function save_register_info($mobile, $pass, $ip ){
				
			/* 注册成功, 保存数据库. */
			/* 随机化生成昵称 */
			$data=array(
	            'user_login' => '',
	            'user_email' => '',
	            'mobile' =>$mobile,
	            'user_nicename' =>'bg_' . $this->getRandChar(4) . substr($mobile,-4,4),
	            'user_pass' => sp_password($pass),
	            'last_login_ip' => $ip,
	            'create_time' => date("Y-m-d H:i:s"),
	            'last_login_time' => date("Y-m-d H:i:s"),
	            'user_status' => 1,
	            "user_type"=>2,//会员
	        );

			/*
			$info['mobile'] = $mobile;
			$info['user_pass'] = sp_password($pass);
			$info['last_login_ip'] = $ip;
			$info['last_login_time'] = date('Y-m-d H:i:s', time());
			$info['create_time'] = date('Y-m-d H:i:s', time());
			$info['user_type'] = 2;
			$info['sex'] = 0;
			$info['user_login'] = $mobile;
			$info['user_nicename'] = $mobile;
			*/

			$this -> add($data);	

	}

	/*
	*	重设密码
	*/
	public function reset_pass_by_mobile($mobile, $pass, $ip){
		$where['mobile'] = $mobile;
		$userID = $this -> where($where) -> getfield('id');

		/*
		dump ($userID);
		*/

		$this -> reset_pass_by_userID($userID, $pass, $ip);
	}

	/*
	*	重设密码
	*/
	public function reset_pass_by_userID($userID, $pass, $ip){
		$where['id'] = $userID;

		/* 修改密码和最后登陆IP */
		$data=array(
	            'user_pass' => sp_password($pass),
	            'last_login_ip' => $ip	            
	        );
			
		$this -> where($where) -> save($data);
	}

	/*
	*	修改手机
	*/
	public function changeMobile($mobileOld, $mobileNew, $ip){
		$where['mobile'] = $mobileOld;

		/* 修改密码和最后登陆IP */
		$data=array(
	            'mobile' => $mobileNew,
	            'last_login_ip' => $ip	            
	        );
			
		$this -> where($where) -> save($data);
	}

	/*
	*	修改用户信息: 昵称, 性别, 邮箱, 签名
	*/
	public function changeUserInfo($ID, $niceName, $sex, $email, $signature){
		$where['id'] = $ID;

		$data=array(
	            'user_nicename' => $niceName,
	            'sex' => $sex,
	            'user_email' => $email,
	            'signature' => $signature	            
	        );
			
		$this -> where($where) -> save($data);
	}

	/*
	*	读取用户信息
	*/
	public function read_user_info($ID){
		$where['id'] = $ID;

		$data = $this -> where($where) -> find();

		/*
		dump($data);
		*/
		
		return $data;
	}

	public function read_user_info_by_mobile($mobile){
		$where['mobile'] = $mobile;

		$data = $this -> where($where) -> find();

		/*
		dump($data);
		*/
		
		return $data;
	}

}